// https://leetcode.cn/problems/reverse-linked-list-ii/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode * dummy = new ListNode(-1);
        dummy->next = head;
        ListNode * start = dummy;
        int i = 1;
        while(i < left){
            start = start->next;
            i++;
        }
        ListNode * prev = start;
        start = start->next;
        ListNode * startDummy = start;
        ListNode * prevDummy = prev;

        ListNode * next = nullptr;
        while(left <= right){
            cout << "left:" << left << endl;
            next = start->next;
            start->next = prev;
            prev = start;
            start = next;
            left++;
        }
        if(next){
            cout << "next:" << next->val << endl;
        }
        if(prev){
            cout << "prev:" << prev->val << endl;
        }

        prevDummy->next = prev;
        startDummy->next = next;

        return dummy->next;
    }

    ListNode * init(){
        ListNode * head1 = new ListNode(1);
        ListNode * head2 = new ListNode(2);
//        ListNode * head3 = new ListNode(3);
//        ListNode * head4 = new ListNode(4);
//        ListNode * head5 = new ListNode(5);
        head1->next = head2;
//        head2->next = head3;
//        head3->next = head4;
//        head4->next = head5;
        return head1;
    }

    void show(ListNode * head){
        while(head){
            cout << head->val << ",";
            head = head->next;
        }
        cout << endl;
    }
};

int main(){
    Solution so;
    ListNode * node = so.init();
    so.show(node);
    ListNode * newNode = so.reverseBetween(node, 1, 2);
    so.show(newNode);
    return 0;
}
